/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ConsultoresDialog.java
 *
 * Created on Oct 22, 2010, 11:06:21 AM
 */
package br.com.tbp.gui;

import br.com.tbp.controle.ControlePedido;
import br.com.tbp.exception.PersistenciaException;
import br.com.tbp.gui.table.JTableUtils;
import br.com.tbp.gui.table.PedidosTableModel;
import br.com.tbp.model.domain.Consultor;
import br.com.tbp.model.domain.Pedido;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import javax.swing.text.MaskFormatter;

/**
 *
 * @author Diego Freire
 */
public class PedidosConsultorDialog extends javax.swing.JDialog {

    private boolean select = false;
    private PedidosTableModel model;
    private ControlePedido controle = new ControlePedido();
    private MenuPrincipal menu;
    private String cnpjMask = "##.###.###/####-##";
    private MaskFormatter maskFormatter;
    private Consultor consultor;

    public PedidosConsultorDialog(java.awt.Frame parent, boolean modal, Consultor consultor) {
        super(parent, modal);
        initComponents();
        if (parent instanceof MenuPrincipal) {
            this.menu = (MenuPrincipal) parent;
        }
        setConsultor(consultor);
        setLocationRelativeTo(null);
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        contentPanel = new javax.swing.JPanel();
        split1 = new javax.swing.JSplitPane();
        buscaPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        fantasiaRadio = new javax.swing.JRadioButton();
        okButton = new javax.swing.JButton();
        cnpjRadio = new javax.swing.JRadioButton();
        idPedidoRadio = new javax.swing.JRadioButton();
        inputTextField = new javax.swing.JFormattedTextField();
        jLabel2 = new javax.swing.JLabel();
        periodoRadio = new javax.swing.JRadioButton();
        inicioField = new org.jdesktop.swingx.JXDatePicker();
        finalField = new org.jdesktop.swingx.JXDatePicker();
        jPanel6 = new javax.swing.JPanel();
        scrollpane = new javax.swing.JScrollPane();
        tabela = new javax.swing.JTable();
        jPanel7 = new javax.swing.JPanel();
        visualizarButton = new javax.swing.JButton();
        fecharButton = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        msgLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Pedidos - [Consulta]");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        contentPanel.setLayout(new java.awt.BorderLayout());

        jLabel1.setText("Busca simples");

        buttonGroup1.add(fantasiaRadio);
        fantasiaRadio.setSelected(true);
        fantasiaRadio.setText("Nome fantasia da empresa");
        fantasiaRadio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fantasiaRadioActionPerformed(evt);
            }
        });

        okButton.setText("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        buttonGroup1.add(cnpjRadio);
        cnpjRadio.setText("CNPJ");
        cnpjRadio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cnpjRadioActionPerformed(evt);
            }
        });

        buttonGroup1.add(idPedidoRadio);
        idPedidoRadio.setText("ID pedido");
        idPedidoRadio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                idPedidoRadioActionPerformed(evt);
            }
        });

        inputTextField.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), javax.swing.BorderFactory.createEmptyBorder(0, 5, 1, 1)));
        inputTextField.setFont(new java.awt.Font("Dialog", 0, 15)); // NOI18N
        inputTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                inputTextFieldActionPerformed(evt);
            }
        });

        jLabel2.setText("> Selecione o filtro abaixo e digite para buscar");

        buttonGroup1.add(periodoRadio);
        periodoRadio.setText("Período");
        periodoRadio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                periodoRadioActionPerformed(evt);
            }
        });

        inicioField.setEnabled(false);

        finalField.setEnabled(false);

        javax.swing.GroupLayout buscaPanelLayout = new javax.swing.GroupLayout(buscaPanel);
        buscaPanel.setLayout(buscaPanelLayout);
        buscaPanelLayout.setHorizontalGroup(
            buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(buscaPanelLayout.createSequentialGroup()
                .addGroup(buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(buscaPanelLayout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addGroup(buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cnpjRadio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(fantasiaRadio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(periodoRadio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(idPedidoRadio, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(buscaPanelLayout.createSequentialGroup()
                                .addComponent(inicioField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(finalField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(buscaPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(buscaPanelLayout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addComponent(inputTextField))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(okButton)))
                .addContainerGap())
        );
        buscaPanelLayout.setVerticalGroup(
            buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(buscaPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(inputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(8, 8, 8)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(fantasiaRadio)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cnpjRadio)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(idPedidoRadio)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(periodoRadio)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(inicioField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(finalField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(161, Short.MAX_VALUE))
        );

        split1.setLeftComponent(buscaPanel);

        jPanel6.setLayout(new java.awt.BorderLayout());

        scrollpane.setPreferredSize(new java.awt.Dimension(800, 500));

        tabela.setFont(new java.awt.Font("Dialog", 0, 13)); // NOI18N
        tabela.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tabela.setRowHeight(18);
        tabela.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tabela.setShowHorizontalLines(false);
        tabela.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabelaMouseClicked(evt);
            }
        });
        scrollpane.setViewportView(tabela);

        jPanel6.add(scrollpane, java.awt.BorderLayout.CENTER);

        jPanel7.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        visualizarButton.setBackground(new java.awt.Color(150, 184, 250));
        visualizarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/cursor16.png"))); // NOI18N
        visualizarButton.setText("Visualizar Pedido");
        visualizarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                visualizarButtonActionPerformed(evt);
            }
        });
        jPanel7.add(visualizarButton);

        fecharButton.setBackground(new java.awt.Color(150, 184, 250));
        fecharButton.setText("Fechar (ESC)");
        fecharButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fecharButtonActionPerformed(evt);
            }
        });
        jPanel7.add(fecharButton);

        jPanel6.add(jPanel7, java.awt.BorderLayout.PAGE_END);

        jPanel3.setLayout(new java.awt.BorderLayout());

        jPanel5.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 4, 1, 1));
        jPanel5.setLayout(new java.awt.BorderLayout());

        msgLabel.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
        msgLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/venda32.png"))); // NOI18N
        msgLabel.setText("mensagem");
        msgLabel.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jPanel5.add(msgLabel, java.awt.BorderLayout.PAGE_END);

        jPanel3.add(jPanel5, java.awt.BorderLayout.LINE_START);

        jPanel6.add(jPanel3, java.awt.BorderLayout.PAGE_START);

        split1.setRightComponent(jPanel6);

        contentPanel.add(split1, java.awt.BorderLayout.CENTER);

        getContentPane().add(contentPanel, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tabelaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelaMouseClicked
        if (evt.getClickCount() == 2) {
            selecionarPedido(tabela.getSelectedRow());
        }
}//GEN-LAST:event_tabelaMouseClicked

    private void visualizarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_visualizarButtonActionPerformed
        selecionarPedido(tabela.getSelectedRow());
}//GEN-LAST:event_visualizarButtonActionPerformed

    private void fecharButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fecharButtonActionPerformed
        dispose();
    }//GEN-LAST:event_fecharButtonActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        try {
            this.refreshUltimosCadastrados(controle.pesquisar(0, 30, getConsultor()));
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        }
    }//GEN-LAST:event_formWindowOpened

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        buscaPedido(inputTextField.getText());
    }//GEN-LAST:event_okButtonActionPerformed

    private void fantasiaRadioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fantasiaRadioActionPerformed
        instalaCnpjMask(false);
        enableFindByPeriodo(false);
        inputTextField.requestFocus();
        inputTextField.selectAll();
    }//GEN-LAST:event_fantasiaRadioActionPerformed

    private void cnpjRadioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cnpjRadioActionPerformed
        instalaCnpjMask(true);
        enableFindByPeriodo(false);
        inputTextField.requestFocus();
        inputTextField.selectAll();
    }//GEN-LAST:event_cnpjRadioActionPerformed

    private void idPedidoRadioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_idPedidoRadioActionPerformed
        instalaCnpjMask(false);
        enableFindByPeriodo(false);
        inputTextField.requestFocus();
        inputTextField.selectAll();
    }//GEN-LAST:event_idPedidoRadioActionPerformed

    private void inputTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_inputTextFieldActionPerformed
        buscaPedido(inputTextField.getText());
}//GEN-LAST:event_inputTextFieldActionPerformed

    private void periodoRadioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_periodoRadioActionPerformed
        enableFindByPeriodo(true);
    }//GEN-LAST:event_periodoRadioActionPerformed

    public static void main(String args[]) {
        //UIManager.put("swing.boldMetal", Boolean.FALSE);
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                PedidosConsultorDialog dialog = new PedidosConsultorDialog(new javax.swing.JFrame(), true, new Consultor(23));
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    private void refresh(Pedido p) {
        List<Pedido> lista = new ArrayList<Pedido>();
        if (p != null) {
            lista.add(p);
        }
        refresh(lista);
    }

    private void refreshUltimosCadastrados(List<Pedido> lista) {
        model = new PedidosTableModel(lista);
        tabela.setModel(model);
        if (lista.isEmpty()) {
            msgLabel.setText("Não há nenhum pedido cadastrado");
        } else if (lista.size() == 1) {
            msgLabel.setText("Último pedido cadastrado");
        } else {
            msgLabel.setText("Últimos " + lista.size() + " pedidos cadastrados");
        }
        JTableUtils.fitAllColumnsWithoutRenderer(tabela);
        inputTextField.requestFocus();
        inputTextField.selectAll();
    }

    private void refresh(List<Pedido> lista) {
        model = new PedidosTableModel(lista);
        tabela.setModel(model);
        if (lista.isEmpty()) {
            msgLabel.setText("Não há nenhum pedido cadastrado");
        } else if (lista.size() == 1) {
            msgLabel.setText("Exibindo 1 pedido cadastrado");
        } else {
            msgLabel.setText("Exibindo " + lista.size() + " pedidos cadastrados");
        }
        JTableUtils.fitAllColumnsWithoutRenderer(tabela);
        inputTextField.requestFocus();
        inputTextField.selectAll();
    }
    // <editor-fold defaultstate="collapsed" desc="Declaration of class members">
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel buscaPanel;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JRadioButton cnpjRadio;
    private javax.swing.JPanel contentPanel;
    private javax.swing.JRadioButton fantasiaRadio;
    private javax.swing.JButton fecharButton;
    private org.jdesktop.swingx.JXDatePicker finalField;
    private javax.swing.JRadioButton idPedidoRadio;
    private org.jdesktop.swingx.JXDatePicker inicioField;
    private javax.swing.JFormattedTextField inputTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JLabel msgLabel;
    private javax.swing.JButton okButton;
    private javax.swing.JRadioButton periodoRadio;
    private javax.swing.JScrollPane scrollpane;
    private javax.swing.JSplitPane split1;
    private javax.swing.JTable tabela;
    private javax.swing.JButton visualizarButton;
    // End of variables declaration//GEN-END:variables

    // </editor-fold>
    public PedidosTableModel getModel() {
        return model;
    }

    @Override
    protected JRootPane createRootPane() {
        ActionListener closeListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                fecharButtonActionPerformed(e);
            }
        };
        KeyStroke stroke =
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        JRootPane myRootPane = new JRootPane();
        myRootPane.registerKeyboardAction(
                closeListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        return myRootPane;
    }

    public boolean isSelect() {
        return select;
    }

    public void setSelect(boolean select) {
        this.select = select;
    }

    private void selecionarPedido(int row) {
        if (row >= 0) {
            setCursor(new Cursor(Cursor.WAIT_CURSOR));
            Pedido pedido = model.getPedido(row);
            if (pedido != null) {
                if (!isSelect()) {
                    try {
                        pedido.limparItens();
                        pedido.limparSituacoesExternas();
                        pedido.limparSituacoesInternas();
                        controle.recuperaItensDePedido(pedido);
                        controle.recuperaSituacoesInternasDoPedido(pedido);
                        controle.recuperaSituacoesDoPedido(pedido);
                    } catch (PersistenciaException pex) {
                        System.out.println(pex.getMessage());
                    }
                    PedidoConsultorDialog dialog = new PedidoConsultorDialog(this.menu, "TBP - Pedido [Somente-Leitura]", true);
                    dialog.setPedido(pedido);
                    dialog.setNovoPedido(false);
                    dialog.setVisible(true);
                }
            }
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        }
    }

    private void buscaPedido(String texto) {
        if ((texto.isEmpty()) && (inputTextField.isEditable())) {
            refresh(new ArrayList<Pedido>());
        } else {
            try {
                if (fantasiaRadio.isSelected()) {
                    refresh(controle.pesquisarPelaEmpresa(texto, getConsultor()));
                } else if (cnpjRadio.isSelected()) {
                    refresh(controle.pesquisarPeloCnpj(texto, getConsultor()));
                } else if (periodoRadio.isSelected()) {
                    Date inicio = inicioField.getDate();
                    if (inicio == null) {
                        inicio = new Date();
                    }
                    Date fim = finalField.getDate();
                    if (fim == null) {
                        fim = inicio;
                    }
                    refresh(controle.pesquisar(inicio, fim, getConsultor()));
                } else if (idPedidoRadio.isSelected()) {
                    try {
                        long id = Long.parseLong(texto);
                        refresh(controle.pesquisar(id, getConsultor()));
                    } catch (NumberFormatException nfe) {
                        refresh(new ArrayList<Pedido>());
                    }
                }
            } catch (PersistenciaException pex) {
                System.out.println(pex.getMessage());
            }
        }
    }

    private void instalaCnpjMask(boolean instalar) {
        if (maskFormatter == null) {
            try {
                maskFormatter = new MaskFormatter(cnpjMask);
            } catch (ParseException pex) {
            }
        }
        if (instalar) {
            maskFormatter.install(inputTextField);
        } else {
            maskFormatter.uninstall();
            inputTextField.setText(null);
        }

    }

    private void enableFindByPeriodo(boolean enabled) {
        inicioField.setEnabled(enabled);
        finalField.setEnabled(enabled);
        inputTextField.setEditable(!enabled);
        inputTextField.setFocusable(!enabled);
        if (enabled) {
            inicioField.requestFocus();
        } else {
            inputTextField.requestFocus();
        }
    }

    public Consultor getConsultor() {
        return consultor;
    }

    public void setConsultor(Consultor consultor) {
        this.consultor = consultor;
    }
}
